package com.bwsoft.portal.service.impl;

import java.util.Date;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.VerificationCode;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.portal.service.CodeService;
import com.bwsoft.util.ruanweisms.RuanweiSmsUtil;
@Service(CodeService.NAME)
public class CodeServiceImpl extends PortalBaseServiceImpl implements CodeService{
	private static Logger LOG = Logger.getLogger(CodeServiceImpl.class);

	/**
	 * 返回四位随机数
	 * @return
	 */
	public String getRandomCode(){
		int code=new Random().nextInt(9999)%(9999-1000+1) + 1000;
		return code+"";
	}
	
	private String sendToPhone(String phoneNumber, String randomCode) {
		LOG.info("正在给手机号为："+phoneNumber+"的用户发送号码为："+randomCode+"的验证码");
		LOG.info("开始调用发送短信接口");
		String returnMsg=RuanweiSmsUtil.sendSms(phoneNumber,randomCode);
		LOG.info("调用发送短信接口结束，反馈报文为："+returnMsg);
		return returnMsg;
	}

	@Override
	public ResponsePojo phoneRegister(String phoneNumber) {
		ResponsePojo rp = new ResponsePojo();
		try {
			
			// 验证数据库中是否有这个用户
			String checkEmailHql = "select count(*) from Account as ac where ac.account=?";
			
			Long count = (Long) accountDao.findByHql(checkEmailHql, phoneNumber).get(0);
			
			if (count>0) {
				rp.setErrcode(1);
				rp.setErrmsg("手机号已注册");
				return rp;
			}

			String randomCode = getRandomCode();

			// 发送短信

			String returnXml=sendToPhone(phoneNumber, randomCode);

			VerificationCode vc = new VerificationCode();
			vc.setNumber(phoneNumber);
			vc.setCode(randomCode);
			vc.setStatus(returnXml.indexOf("Success")>0);
			vc.setSendTime(new Date());
			vc.setMessage(returnXml);
			verificationCodeDao.save(vc);
			rp.setErrcode(0);
			rp.setErrmsg(vc.getStatus()?"发送成功":"发送失败："+returnXml.substring(returnXml.indexOf("<message>")+9, returnXml.indexOf("</message>")));
			
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("发送短信异常："+e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
		}
		return rp;
	}
	
	
	
	
}
